package com.zbkj.admin.task.mszs;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbkj.common.constants.MszsConstants;
import com.zbkj.common.model.mszs.MszsOrder;
import com.zbkj.common.model.mszs.MszsRoom;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.service.service.mszs.MszsOrderService;
import com.zbkj.service.service.mszs.MszsRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * 民宿助手-订单退款状态-同步处理task
 * @author lingfe
 */
@Slf4j
@Component
@Configuration //读取配置
@EnableScheduling // 2.开启定时任务
public class MszsOrderRefundSynTask {

    @Autowired
    private MszsOrderService mszsOrderService;

    @Autowired
    private MszsRoomService mszsRoomService;

    @Scheduled(fixedDelay = 1000 * 60L) //60s-同步一次数据
    public void init(){
        log.info("---民宿助手-订单退款-同步处理task: Execution Time - {}", DateUtil.nowDateTime());
        try {
            //定义查询对象-订单
            LambdaQueryWrapper<MszsOrder> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(MszsOrder::getOrderStatusNumber, MszsConstants.MSZS_ORDER_STATUS_INT_Refunded);
            lambdaQueryWrapper.notIn(MszsOrder::getRoomId,0);
            List<MszsOrder> orderList = mszsOrderService.list(lambdaQueryWrapper);

            //处理数据
            orderList.forEach(order->{
                //更新房间状态-清房
                MszsRoom room = mszsRoomService.getById(order.getRoomId());
                Optional.ofNullable(room).ifPresent(roomInfo->{
                    roomInfo.setStatus(MszsConstants.MSZS_ROOM_STATUS_INT_Pending_check_in);
                    mszsRoomService.updateById(roomInfo);
                });

                //解除订单与房间的绑定关系
                order.setRoomId(0);
                order.setOrderStatus(MszsConstants.MSZS_ORDER_STATUS_STR_Refunded);
                order.setOrderStatusNumber(MszsConstants.MSZS_ORDER_STATUS_INT_Refunded);
                mszsOrderService.updateById(order);
            });
        }catch (Exception e){
            log.error("---民宿助手-订单退款-同步处理task-发生错误:" + " | msg : {}", e.getMessage());
            e.printStackTrace();
        }
    }
}
